<?php
/**
 * Created by PhpStorm.
 * User: zgh
 * Date: 2021-07-30
 * Time: 17:09
 */

namespace app\api\service;


use app\api\validate\LoginValidate;
use app\common\exception\ServiceException;
use app\common\model\SmsModel;
use app\common\model\UserModel;
use app\common\service\SmsService;
use app\common\util\EncryptUtil;
use app\common\util\RedisUtil;
use think\facade\Request;


class LoginService
{
    const LOGIN_TYPE_CODE = 1;
    const LOGIN_TYPE_PASSWORD = 2;

    const PASSWORD_SALT = 'Hua!09302I**';


    public static function getTokenPrefix()
    {
        return config("cache.redis.prefix") . "user_token:";
    }

    public static function sendSms($params)
    {
        $validate = new LoginValidate();
        if (!$validate->scene(LoginValidate::SEND_SMS)->check($params)) {
            throw  new ServiceException($validate->getError());
        }
        $code = rand(100000, 999999);
        $res = SmsService::sendSms($params['mobile'], $code);
        return $res;
    }


    public static function doLogin($params)
    {
        $validate = new LoginValidate();
        if (!$validate->scene(LoginValidate::LOGIN_TYPE)->check($params)) {
            throw  new ServiceException($validate->getError());
        }
        $user = UserModel::where(['mobile' => $params['mobile']])->where([["status", "<>", -1]])->find();
        if ($params['login_type'] == self::LOGIN_TYPE_CODE) {
            if (!($sms_model = SmsModel::where(['mobile' => $params['mobile'], "type" => 1, 'is_check' => 0])->order(['id' => 'desc'])->find())) {
                throw new ServiceException("请先发送验证码");
            }
            if ($sms_model->expire_time <= time()) {
                throw new ServiceException("验证码已经失效!");
            }
            if ($sms_model->verify_code != $params['verify_code']) {
                throw new ServiceException("验证码输入错误!");
            }
            $sms_model->is_check = 1;
            $sms_model->save();
        } else {
            if (empty($user)) {
                throw new ServiceException("用户还没有注册!");
            }
            if (EncryptUtil::Encrypt($params['password'], self::PASSWORD_SALT) !== $user->password) {
                throw new ServiceException("密码错误！");
            }
        }
        if (empty($user)) {
            $user = new UserModel();
            $user->mobile = $params['mobile'];
            $user->register_time = current_datetime();
            $user->nickname = '用户' . substr($params['mobile'], -4, 4);
        }
        $user->ip = request()->ip();
        $user->login_time = current_datetime();
        $user->save();
        self::clearToken();
        $token = self::cacheUserLoginToken($user->id);
        $data['utk'] = $token;
        $data['status'] = $user->status;
        $data['user_id'] = $user->id;
        return $data;
    }


    /**
     * 清除之前的token信息
     */
    public static function clearToken($token = "")
    {
        if (empty($token)) {
            $token = Request::param("utk", "");
        }
        if ($token) {
            $redisUtil= new RedisUtil(); $redis = $redisUtil->getHandler();
            $redis->del(self::getTokenPrefix() . $token);
        }
        return true;
    }

    public static function cacheUserLoginToken($user_id = 0, $expire = 0)
    {
        $redisUtil= new RedisUtil(); $redis = $redisUtil->getHandler();
        $token = md5(uniqid() . $user_id . time());
        $expire = !empty($expire) && is_numeric($expire) && $expire > 0 ? $expire : 86400 * 7; //有效期，单位：秒
        $redis->set(self::getTokenPrefix() . $token, $user_id, $expire);
        return $token;
    }


    public static function getUserIdByTokenFromCache($token)
    {
        $redisUtil= new RedisUtil(); $redis = $redisUtil->getHandler();
        $uid = $redis->get(self::getTokenPrefix() . $token);
        return $uid ?: 0;
    }


    /**
     * 通过token 获取第三方登陆信息
     * utk
     * @param $token
     */
    public static function getThirdInfoByCacheToken($token = "")
    {
        $info = [];
        if (empty($token)) {
//                $token = isset();
        }
    }

//        public static function

    public static function thirdDoLogin($params)
    {

    }

}